<template>

  <el-select v-model="key" class="filter-item" clearable :placeholder="placeholder" @clear="clearOption">
    <el-option :value="key" :label="label" :style="'height: '+treeHeight+'px;width:240px;padding: 0;'">
      <el-tree
        ref="tree"
        :data="nodes"
        node-key="id"
        class="permission-tree"
        style="height: 100%"
        default-expand-all
        :check-strictly="true"
        show-checkbox
        @check="checkGroupNode"
      >
                <span class="custom-tree-node" slot-scope="{ node, data }">
                    <span>
                        <i :class="data.icon"></i>{{ data.name }}&nbsp;
                    </span>
                </span>
      </el-tree>
    </el-option>
  </el-select>

</template>

<script>

export default {
  name: 'TreeSelect',
  props: {
    nodes: undefined,
    placeholder: undefined,
    value: 0
  },
  data() {
    return {
      map: new Map(),
      key: this.value
    }
  },
  computed: {
    treeHeight() {
      const len = this.parseTree(0, this.$props.nodes)
      this.key = this.value
      this.$nextTick(() => {
        this.$refs.tree.setCheckedKeys([this.key]);
      })
      return len * 26
    },
    label: {
      get(){
        this.$nextTick(() => {
          this.$refs.tree.setCheckedKeys([this.key]);
        })
        return this.map.get(this.key)
      },
      set(newValue){
        return newValue
      }
    }
  },
  mounted() {

  },
  methods: {
    checkGroupNode: function (a, b) {
      if (b.checkedKeys.length > 0) {
        this.$refs.tree.setCheckedKeys([a.id]);
        this.key = a.id
        this.label = a.name
        //将v-model绑定向父节点传递,更新父节点的v-model
        this.$emit('input',this.key)
      }
    },
    parseTree(i, tree){
      tree.forEach(item => {
        i++
        this.map.set(item.id,item.name)
        if (item.children) {
          i = this.parseTree(i, item.children)
        }
      })
      return i
    },
    clearOption(){
      this.$emit('input',undefined)
    }
  }
}
</script>

<style lang="scss" scoped>

</style>
